package org.idea.qiyu.framework.gateway.starter;

import org.idea.qiyu.framework.gateway.starter.registry.ApplicationRegistry;
import org.idea.qiyu.framework.gateway.starter.registry.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 将各个SpringBoot应用注册到zk上
 *
 * @Author linhao
 * @Date created in 10:24 上午 2022/4/16
 */
public class GatewayApplicationRegistryHandler implements ApplicationListener<WebServerInitializedEvent>, ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(GatewayApplicationRegistryHandler.class);

    @Value("${spring.application.name}")
    private String applicationName;

    private volatile ApplicationContext applicationContext;

    private volatile ApplicationRegistry applicationRegistry;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        System.out.println("注册服务到zk上，并且通知gateway暴露服务 【start】");
        try {
            InetAddress localHost = Inet4Address.getLocalHost();
            String ip = localHost.getHostAddress();
            Integer port = webServerInitializedEvent.getWebServer().getPort();
            URL url = new URL();
            url.setAddress(ip);
            url.setApplicationName(applicationName);
            url.setPort(port);
            url.setRegistryTime(System.currentTimeMillis());
            url.setStatus(0);
            url.setWeight(100);
            applicationRegistry.registry(url);
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
        }
        System.out.println("注册服务到zk上，并且通知gateway暴露服务 【end】");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        this.applicationRegistry = applicationContext.getBean(ApplicationRegistry.class);
    }
}
